package ar.edu.unq.wannaplay.errors;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import org.apache.log4j.Logger;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;

@Aspect
public class ErrorHandling {
    private static final Logger LOG = Logger.getLogger(ErrorHandling.class);

    @Around("execution(* ar.edu.unq.wannaplay.services.*.*(..))")
    public Object aroundErrors(final ProceedingJoinPoint pjp) throws Throwable {
        Object obj = null;
        try {
            obj = pjp.proceed();
        } catch (Exception e) {
            String name = pjp.getSignature().getName();
            Method[] methods = pjp.getClass().getMethods();
            if (!this.methodExceptionIsMine(name, methods, e)) {
                LOG.info(e.getMessage());
            }
            throw e;
        }
        return obj;
    }

    private boolean methodExceptionIsMine(final String name, final Method[] methods, final Exception exception) {
        List<Class<?>> exceptions = new ArrayList<Class<?>>();
        for (Method m : methods) {
            if (m.getName().equals(name)) {
                exceptions = Arrays.asList(m.getExceptionTypes());
            }
        }
        return exceptions.contains(exception.getClass());
    }
}
